﻿using System.Web.Mvc;
using Infrastructure.Base.Services;
using Infrastructure.Mvc.SeedWork.Extensions;
using Infrastructure.Mvc.SeedWork.Models.Message;
using Infrastructure.Mvc.SeedWork.Models.ViewContent;
using Infrastructure.Mvc.SeedWork.Resources;

namespace Infrastructure.Mvc.SeedWork.ControlContent
{
    public class PortalBaseController : Controller
    {
        public string ReturnUrl
        {
            get { return (Session["ReturnUrl"] ?? Url.ActionForUrl("List")).ToString(); }
            set { Session["ReturnUrl"] = value; }
        }

        protected UserModel UserContext
        {
            get { return ManageContext.Instance.User; }
        }

        protected PageModel PageContext
        {
            get { return ManageContext.Instance.Page; }
        }

        #region 页面成功

        private string GetUrl()
        {
            if (!string.IsNullOrWhiteSpace(Request["returnUrl"]))
            {
                return Request["returnUrl"];
            }
            return ReturnUrl;
        }

        protected virtual ViewResult PageSuccess(string msg, string nextUrl, string nextTitle,
            string preOperation = "返回列表",
            string view = "", object data = null)
        {
            var message = new MessageModel
            {
                Type = MessageType.Success,
                Msg = new MvcHtmlString(msg),
                BackUrl = GetUrl(),
                BackTitle = preOperation ?? "返回列表",
                Title = Messages.PortalBaseController_PageSuccess_Title,
                Data = data,
            };
            ReturnUrl = null;
            return View(view, message);
        }

        #endregion

        #region 页面错误

        protected void AlterMsg(string msg)
        {
            Response.Write("<script>alert('" + msg + "')</script>");
        }

        protected void PageSuccessToList()
        {
            Response.Redirect(Request.UrlReferrer.ToString());
        }

        protected virtual ViewResult PageError(string msg, string nextUrl, string nextTitle,
            string preOperation = "返回列表",
            string view = "", object data = null)
        {
            var message = new MessageModel
            {
                Type = MessageType.Error,
                Msg = new MvcHtmlString(msg),
                BackUrl = ReturnUrl,
                BackTitle = preOperation,
                Title = Messages.PortalBaseController_PageError_Title,
                Data = data,
            };
            ReturnUrl = null;
            return View(view, message);
        }

        protected virtual ViewResult PageMessage(MessageModel msgModel, string view = "")
        {
            return View(view, msgModel);
        }

        #endregion
    }
}